﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using HtmlAgilityPack;
using Kooboo.HtmlFunc.Providers;

namespace Kooboo.HtmlFunc.Function
{
    public class FuncPool
    {
        static Dictionary<FuncType, IFuncEntity> FuncDictionary;

        static FuncPool()
        {
            LoadFuncDictionary();
            AddFileWatcher();
        }

        private static void LoadFuncDictionary()
        {
            FuncDictionary = new Dictionary<FuncType, IFuncEntity>();
            if (!string.IsNullOrWhiteSpace(AnalysisSetting.FuncFilePath) &&
                File.Exists(AnalysisSetting.FuncFilePath))
            {
                var setting = RuntimeKit.XmlDeserialize<FuncSetting>(AnalysisSetting.FuncFilePath);
                foreach (var entity in setting)
                    FuncDictionary.Add(entity.FuncType, entity);
            }
            else
            {
                var stream = RuntimeKit.LoadEmbeddedResource("FuncSetting.xml");
                var setting = RuntimeKit.XmlDeserialize<FuncSetting>(stream);
                foreach (var entity in setting)
                    FuncDictionary.Add(entity.FuncType, entity);
            }
        }

        private static void AddFileWatcher()
        {
            //var watcher = new FileSystemWatcher(ParserSettings.FuncFilePath);
            //watcher.NotifyFilter = NotifyFilters.LastWrite;
            //watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            //watcher.EnableRaisingEvents = true; // begin
        }

        static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            lock (typeof(FuncPool))
            {
                LoadFuncDictionary();
            }
        }

        public static IFuncEntity GetFunc(FuncType type)
        {
            if (!FuncDictionary.ContainsKey(type))
            {
                throw new Exceptions.FuncNotSupportException(type);
            }

            return FuncDictionary[type];
        }
    }
}
